import { useState, useEffect } from 'react'
import apiService from '../utils/api.js'
import { ARTIST_GENDER_OPTIONS, ARTIST_TYPE_OPTIONS, ARTIST_NATIONALITY_OPTIONS, getGenderLabel, getTypeLabel, getNationalityLabel } from '../utils/constants.js'
import Pagination from './Pagination.jsx'

const ArtistsManagement = () => {
  // 歌手管理相关状态
  const [artists, setArtists] = useState([])
  const [isAddingArtist, setIsAddingArtist] = useState(false)
  const [isEditingArtist, setIsEditingArtist] = useState(false)
  const [currentArtist, setCurrentArtist] = useState(null)
  const [artistFormData, setArtistFormData] = useState({
    name: '',
    gender: '',
    type: '',
    nationality: '',
    avatarUrl: 'https://via.placeholder.com/300',
    description: ''
  })
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)
  const [avatarFile, setAvatarFile] = useState(null) // 存储用户选择的头像文件
  
  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1)
  const [totalItems, setTotalItems] = useState(0)
  const [itemsPerPage, setItemsPerPage] = useState(10)

  // 获取歌手列表
  const fetchArtists = async (page = currentPage) => {
    try {
      setLoading(true)
      const params = {
        page,
        limit: itemsPerPage
      }
      const response = await apiService.getArtists(params)
      if (response.code === 200 && response.data) {
        setArtists(response.data.data || [])
        setTotalItems(response.data.meta.total || 0)
      } else {
        // 如果API调不通，使用模拟数据
        setArtists([
        ])
        setTotalItems(0)
      }
    } catch (error) {
      console.error('获取歌手列表失败:', error)
      setError('获取歌手列表失败')
      // 使用模拟数据
      setArtists([
      ])
      setTotalItems(0)
    } finally {
      setLoading(false)
    }
  }

  // 组件首次加载时获取歌手列表
  useEffect(() => {
    fetchArtists()
  }, [])

  // 处理分页变化
  const handlePageChange = (page) => {
    setCurrentPage(page)
    fetchArtists(page)
  }

  // 准备添加歌手
  const prepareAddArtist = () => {
    setArtistFormData({ name: '', gender: '', type: '', nationality: '', avatarUrl: 'https://via.placeholder.com/300', description: '' })
    setAvatarFile(null) // 重置头像文件
    setIsAddingArtist(true)
    setIsEditingArtist(false)
    setCurrentArtist(null)
  }

  // 准备编辑歌手
  const prepareEditArtist = (artist) => {
    setCurrentArtist(artist)
    setArtistFormData({
      name: artist.name,
      gender: artist.gender || '',
      type: artist.type || '',
      nationality: artist.nationality || '',
      avatarUrl: artist.avatarUrl || 'https://via.placeholder.com/300',
      description: artist.description || ''
    })
    setAvatarFile(null) // 重置头像文件
    setIsEditingArtist(true)
    setIsAddingArtist(false)
  }

  // 取消添加/编辑歌手
  const cancelArtistAction = () => {
    setIsAddingArtist(false)
    setIsEditingArtist(false)
    setCurrentArtist(null)
    setArtistFormData({
      name: '',
      gender: '',
      type: '',
      nationality: '',
      avatarUrl: 'https://via.placeholder.com/300',
      description: ''
    })
    setAvatarFile(null) // 重置头像文件
  }

  // 处理添加歌手
  const handleAddArtist = async (e) => {
    e.preventDefault()
    try {
      // 先创建歌手
      const artistResponse = await apiService.addArtist(artistFormData)
      
      // 如果用户选择了新头像，上传头像
      if (avatarFile && artistResponse.code === 200 && artistResponse.data?.id) {
        try {
          const avatarResponse = await apiService.uploadSingerAvatar(artistResponse.data.id, avatarFile)
          if (avatarResponse.code !== 200) {
            console.warn('头像上传失败，但歌手创建成功')
          }
        } catch (avatarError) {
          console.warn('头像上传失败，但歌手创建成功:', avatarError)
        }
      }
      
      cancelArtistAction()
      fetchArtists()
    } catch (error) {
      console.error('添加歌手失败:', error)
      setError('添加歌手失败，请重试')
    }
  }

  // 处理编辑歌手
  const handleEditArtist = async (e) => {
    e.preventDefault()
    try {
      if (currentArtist) {
        // 先更新歌手信息
        await apiService.updateArtist(currentArtist.id, artistFormData)
        
        // 如果用户选择了新头像，上传头像
        if (avatarFile) {
          try {
            const avatarResponse = await apiService.uploadSingerAvatar(currentArtist.id, avatarFile)
            if (avatarResponse.code !== 200) {
              console.warn('头像上传失败，但歌手信息更新成功')
            }
          } catch (avatarError) {
            console.warn('头像上传失败，但歌手信息更新成功:', avatarError)
          }
        }
        
        cancelArtistAction()
        fetchArtists()
      }
    } catch (error) {
      console.error('更新歌手失败:', error)
      setError('更新歌手失败，请重试')
    }
  }

  // 处理删除歌手
  const handleDeleteArtist = async (artistId) => {
    if (window.confirm('确定要删除这个歌手吗？')) {
      try {
        await apiService.deleteArtist(artistId)
        fetchArtists()
      } catch (error) {
        console.error('删除歌手失败:', error)
        setError('删除歌手失败，请重试')
      }
    }
  }

  // 处理头像上传（只做本地预览）
  const handleAvatarUpload = (e) => {
    const file = e.target.files[0]
    if (!file) return
    
    // 存储选择的文件
    setAvatarFile(file)
    
    // 创建本地预览URL
    const previewUrl = URL.createObjectURL(file)
    setArtistFormData(prev => ({ ...prev, avatarUrl: previewUrl }))
    
    // 注意：URL.createObjectURL创建的对象需要在不需要时释放，避免内存泄漏
    // 在组件卸载或选择新文件时释放
    return () => {
      if (previewUrl) {
        URL.revokeObjectURL(previewUrl)
      }
    }
  }
  
  // 处理表单输入变化
  const handleInputChange = (e) => {
    const { name, value } = e.target
    setArtistFormData(prev => ({ ...prev, [name]: value }))
  }

  return (
    <>
      <div className="section-header">
        <button className="btn-add" onClick={prepareAddArtist}>
          添加歌手
        </button>
      </div>

      {error && (
        <div className="error-message">
          {error}
          <button onClick={() => setError('')}>×</button>
        </div>
      )}

      {loading ? (
        <div className="loading">加载中...</div>
      ) : (
        <div className="songs-table-container">
          <table className="songs-table" style={{ tableLayout: 'fixed' }}>
            <thead>
              <tr>
                <th>ID</th>
                <th>头像</th>
                <th>歌手名称</th>
                <th>性别</th>
                <th>类型</th>
                <th>歌手分类</th>
                <th style={{ width: '300px' }}>描述</th>
                <th style={{width: '200px'}}>操作</th>
              </tr>
            </thead>
            <tbody>
              {artists.map(artist => (
                <tr key={artist.id}>
                  <td>{artist.id}</td>
                  <td>
                    <img 
                      src={artist.avatarUrl} 
                      alt={artist.name} 
                      className="song-cover-small"
                    />
                  </td>
                  <td>{artist.name}</td>
                    <td>{getGenderLabel(artist.gender)}</td>
                    <td>{getTypeLabel(artist.type)}</td>
                    <td>{getNationalityLabel(artist.nationality)}</td>
                    <td style={{ width: '500px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{artist.description || '-'}</td>
                  <td>
                    <button 
                      className="btn-edit"
                      onClick={() => prepareEditArtist(artist)}
                    >
                      编辑
                    </button>
                    <button 
                      className="btn-delete"
                      onClick={() => handleDeleteArtist(artist.id)}
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          
          {/* 分页组件 */}
          <div className="pagination-container">
            <Pagination
              currentPage={currentPage}
              totalPages={Math.ceil(totalItems / itemsPerPage)}
              totalItems={totalItems}
              itemsPerPage={itemsPerPage}
              onPageChange={handlePageChange}
            />
          </div>
        </div>
      )}

      {/* 添加/编辑歌手表单 */}
      {(isAddingArtist || isEditingArtist) && (
        <div className="song-form-modal">
          <div className="song-form">
            <h3>{isAddingArtist ? '添加歌手' : '编辑歌手'}</h3>
            <form onSubmit={isAddingArtist ? handleAddArtist : handleEditArtist}>
              <div className="form-row">
                <div className="form-group">
                  <label htmlFor="artistName">歌手名称</label>
                  <input
                    type="text"
                    id="artistName"
                    name="name"
                    value={artistFormData.name}
                    onChange={handleInputChange}
                    required
                  />
                </div>
                <div className="form-group">
                  <label htmlFor="artistGender">性别</label>
                  <select
                    id="artistGender"
                    name="gender"
                    value={artistFormData.gender}
                    onChange={handleInputChange}
                  >
                    {ARTIST_GENDER_OPTIONS.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="form-group">
                  <label htmlFor="artistType">类型</label>
                  <select
                    id="artistType"
                    name="type"
                    value={artistFormData.type}
                    onChange={handleInputChange}
                  >
                    {ARTIST_TYPE_OPTIONS.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="form-group">
                  <label htmlFor="artistNationality">歌手分类</label>
                  <select
                    id="artistNationality"
                    name="nationality"
                    value={artistFormData.nationality}
                    onChange={handleInputChange}
                  >
                    {ARTIST_NATIONALITY_OPTIONS.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              
              <div className="form-group">
                <label htmlFor="artistAvatar">头像上传</label>
                <div className="avatar-upload-container">
                  <img 
                    width={100}
                    height={100}
                    src={artistFormData.avatarUrl} 
                    alt="歌手头像预览" 
                    className="avatar-preview"
                  />
                  <input
                    type="file"
                    id="avatarUpload"
                    onChange={handleAvatarUpload}
                    accept="image/*"
                    className="avatar-upload-input"
                  />
                  <label htmlFor="avatarUpload" className="avatar-upload-label">
                    {isEditingArtist ? '更换头像' : '上传头像'}
                  </label>
                </div>
              </div>
              
              <div className="form-group">
                <label htmlFor="artistDescription">描述</label>
                <textarea
                  id="artistDescription"
                  name="description"
                  value={artistFormData.description}
                  onChange={handleInputChange}
                  rows="4"
                />
              </div>
              
              <div className="form-actions">
                <button type="button" onClick={cancelArtistAction}>取消</button>
                <button type="submit">保存</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </>
  )
}

export default ArtistsManagement